﻿using Iworld.Author.Manager;
using Iworld.Author.Model;
using Iworld.basis.Service;
using Iworld.Basis.Help;
using Iworld.Basis.Manager;
using Iworld.Game.Manager;
using Iworld.Main.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Iworld.Author.Service.Client.Import
{
    /// <summary>
    /// 赠送金币
    /// </summary>
    [DataContract]
    public class GiveGoldsImport : CheckAuthorImportBase, IPackageForCreateModel<IModelToDbContextOfAuthor,GiveGoldsRecord>
    {
        /// <summary>
        /// 赠送给的账号名称
        /// </summary>
        [DataMember]
        public string Account { set; get; }

        /// <summary>
        /// 赠送的金币数量
        /// </summary>
        [DataMember]
        public double Golds { set; get; }

        /// <summary>
        /// 描述
        /// </summary>
        [DataMember]
        public string Description { set; get; }

        /// <summary>
        /// 二级密码
        /// </summary>
        [DataMember]
        public string TwoLevelPassword { get; set; }


        private GiveGoldsRecord data;

        public void CheckData(IModelToDbContextOfAuthor db)
        {
            if (this.Self.Account == this.Account)
            {
                throw new Exception("赠送金币失败,不能赠送给自己");
            }
            if (this.TwoLevelPassword == null || this.Self.TwoLevelPassword != EncryptHelper.EncryptByMd5(this.TwoLevelPassword))
            {
                throw new Exception("赠送金币失败,二级密码不正确");
            }
            if(BettingManager.IsBetting(this.Self.Id))
            {
                throw new Exception("游戏压分时不能赠送金币,请等待压分局结束在操作");
            }
            Iworld.Author.Model.Author user = db.Authors.FirstOrDefault(x => x.Id == UserId);
            if (user == null) throw new Exception("赠送金币失败,当前用户不存在");
            if (user.Golds < Golds)
            {
                throw new Exception("赠送金币失败,余额不足");
            }
            Iworld.Author.Model.Author userTo = db.Authors.FirstOrDefault(x => x.Account == this.Account);
            if (userTo == null)
            {
                throw new Exception("赠送金币失败,[" + this.Account + "]用户不存在");
            }
            data = new GiveGoldsRecord() { To = userTo, From = user, Golds = Golds, Description = Description };
        }

        public GiveGoldsRecord GetModel(IModelToDbContextOfAuthor db)
        {
            return data;
        }
    }
}
